// Copyright (c) 2017 Uber Technologies, Inc.
// SPDX-License-Identifier: Apache-2.0

import { handleActions } from 'redux-actions';

import { fetchDependencies } from '../actions/jaeger-api';

type DependenciesState = {
  dependencies: any[];
  loading: boolean;
  error: any;
};

const initialState: DependenciesState = {
  dependencies: [],
  loading: false,
  error: null,
};

function fetchStarted(state: DependenciesState): DependenciesState {
  return { ...state, loading: true };
}

function fetchDepsDone(state: DependenciesState, { payload }: any): DependenciesState {
  return { ...state, dependencies: payload.data, loading: false };
}

function fetchDepsErred(state: DependenciesState, { payload: error }: any): DependenciesState {
  return { ...state, error, dependencies: [], loading: false };
}

export default handleActions(
  {
    [`${fetchDependencies}_PENDING`]: fetchStarted,
    [`${fetchDependencies}_FULFILLED`]: fetchDepsDone,
    [`${fetchDependencies}_REJECTED`]: fetchDepsErred,
  },
  initialState
);
